<template>
  <div class="pagination">
    <button :disabled="pageNo <= 1" @click="changepageNo(pageNo - 1)">
      上一页
    </button>
    <button v-if="pageCounts.openPage > 1" @click="changepageNo(1)">1</button>
    <button v-if="pageCounts.openPage > 2">···</button>

    <button
      v-for="item in pageContentArr"
      :key="item"
      :class="pageNo === item ? 'active' : ''"
      @click="changepageNo(item)"
    >
      {{ item }}
    </button>

    <button v-if="pageCounts.openEndPage < totalPages - 1">···</button>
    <button
      v-if="pageCounts.openEndPage < totalPages"
      @click="changepageNo(totalPages)"
    >
      {{ totalPages }}
    </button>
    <button :disabled="pageNo >= totalPages" @click="changepageNo(pageNo + 1)">
      下一页
    </button>
    <button style="margin-left: 30px">当前在:{{ pageNo }}页</button>
  </div>
</template>

<script>
export default {
  name: 'Pagination',
  props: ['totalPages', 'showPageCount', 'pageNo'],
  mounted() {
    console.log(this.totalPages, this.showPageCount, this.pageNo)
  },
  data() {
    return {}
  },
  computed: {
    pageCounts() {
      let openPage = this.pageNo - Math.floor(this.showPageCount / 2)
      let openEndPage = this.pageNo + Math.floor(this.showPageCount / 2)
      if (openPage < 1) {
        openPage = 1
        openEndPage = this.showPageCount
      }
      if (openEndPage > this.totalPages) {
        openEndPage = this.totalPages
        openPage = this.totalPages - this.showPageCount + 1
      }
      //   for (let index = 0; index < this.countPage; index++) {
      //     arr.push(openPage)
      //     openPage++
      //   }
      //   console.log(arr)
      return { openPage, openEndPage }
    },
    pageContentArr() {
      let arr = []
      if (this.totalPages < this.showPageCount) {
        for (let index = 1; index <= this.totalPages; index++) {
          arr.push(index)
        }
      } else {
        let { openPage, openEndPage } = this.pageCounts
        for (let index = openPage; index <= openEndPage; index++) {
          arr.push(index)
        }
      }
      return arr
    },
  },
  methods: {
    changepageNo(PageNo) {
      this.$emit('changePageNo', PageNo)
    },
  },
}
</script>

<style lang="less" scoped>
.pagination {
  button {
    margin: 0 5px;
    background-color: #f4f4f5;
    color: #606266;
    outline: none;
    border-radius: 2px;
    padding: 0 4px;
    vertical-align: top;
    display: inline-block;
    font-size: 13px;
    min-width: 35.5px;
    height: 28px;
    line-height: 28px;
    cursor: pointer;
    box-sizing: border-box;
    text-align: center;
    border: 0;

    &[disabled] {
      color: #c0c4cc;
      cursor: not-allowed;
    }

    &.active {
      cursor: not-allowed;
      background-color: #409eff;
      color: #fff;
    }
  }
}
</style>
